package top.wenzz.commons.entity;

import lombok.Builder;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * Created by 钟廷员 on 2017/7/12.
 */
@Data
@Builder
public class LoginUser implements UserDetails {
    private int id;
    private String username;
    private String password;
    private String salt;
    private long accountExpiredTime;
    private long credentialsExpiredTime;
    private long accountLockedTime;
    private int enable;
    private List<SysMenu> menus;
    private Set<String> permissions;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
        permissions.forEach(p -> list.add(new SimpleGrantedAuthority("ROLE_".concat(p))));
        return list;
    }

    @Override
    public boolean isAccountNonExpired() {
        return System.currentTimeMillis() - this.accountExpiredTime < 0;
    }

    @Override
    public boolean isAccountNonLocked() {
        return System.currentTimeMillis() - this.accountLockedTime > 0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return System.currentTimeMillis() - this.credentialsExpiredTime < 0;
    }

    @Override
    public boolean isEnabled() {
        return this.getEnable() == 1;
    }
}
